package com.geely.design.pattern.structural.facade;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * Created by geely
 * 门面模式
 */
public class GiftExchangeService {
    private QualifyService qualifyService = new QualifyService();
    private PointsPaymentService pointsPaymentService = new PointsPaymentService();
    private ShippingMsgService shippingMsgService = new ShippingMsgService();

    TransactionTemplate transactionTemplate;

    MqService mqService;

    /**
     * 这里涉及分布式事务解决方案
     * @param pointsGift
     */
    public void giftExchange(final PointsGift pointsGift){
        if(qualifyService.isAvailable(pointsGift)){

            transactionTemplate.execute(new TransactionCallbackWithoutResult(){
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                    //资格校验通过
                    if(pointsPaymentService.pay(pointsGift)){
                        //如果支付积分成功
                        shippingMsgService.createMessage(pointsGift);
                    }
                }});
            //事务提交后立马发条消息，通知下游处理。即使发送失败也有兜底job异步扫表发送再次发送消息
            mqService.send(pointsGift);
            shippingMsgService.updateSuccess(pointsGift);

        }
    }

}
